<?php
namespace app\common\controller;

use think\Controller;
use think\Db;
use think\cache\driver\Redis;
use app\common\logic\FfcPayment;

class FfcAll extends Controller
{
    protected $czid;
    protected $time;
    protected $redis;

    public function _initialize()
    {
        parent::_initialize();
        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        $this->czid = '62';
        $this->time = time();
        $this->redis = new Redis();
    }

/************************************开奖   sTART ****************************************************/ 


	
	//统计大小单双
	static private function getCurrentResult($qihao,$czid=62){
		// $list = Db::name("touzhu_list_no")->field("tzhm,tzje")->where(['czid'=>$czid,'qihao'=>$qihao])->where('tzhm','in',['单','双','大','小'])->select();
		$filter = Db::name('caipiao_open')->where(['czid'=>$czid,'filter'=>1])->column('wfid');
		$array_ret = array();
		foreach ($filter as $filt){
			$list = Db::name("touzhu_list_no")->field("tzhm,tzje")->where(['czid'=>$czid,'qihao'=>$qihao])->where('wfid',$filt)->select();
			$ret = ['single'=>0,'double'=>0,'big'=>0,'small'=>0];
			foreach($list as $v){
				$v['tzhm'] = explode(' ',$v['tzhm']);
				if(in_array('单',$v['tzhm'])!==false) {
						
					$ret['single']+=$v['tzje']/count($v['tzhm']);
				}
				if(in_array('双',$v['tzhm'])!==false) {
						
					$ret['double']+=$v['tzje']/count($v['tzhm']);
				}
				if(in_array('大',$v['tzhm'])!==false) {
						
					$ret['big']+=$v['tzje']/count($v['tzhm']);
				}
				if(in_array('小',$v['tzhm'])!==false) {
						
					$ret['small']+=$v['tzje']/count($v['tzhm']);
				}
					
			}
			$array_ret[$filt] = $ret;
		}
        return $array_ret;
    }
	 /**
     * 开奖结果计算
     */
    public function kj_index() {
		$big =1;   //大
		$small = 2; //小
		$single =3;    //单
		$double =4;    //双
		$kjj = array();
		$dig_small ='';
		$he = 0;
		$jg = array();
		$zonghe = array();
		$ks = array();
		$weizhi = array('87'=>'万位','88'=>'千位','89'=>'百位','90'=>'十位','91'=>'个位');
		//获取最新应开奖期号
        $info = Db::name('kjjg_list')->where(['czid'=>$this->czid,'kjjg'=>'0'])->field('qihao,jztime')->where('jztime','<',$this->time)->order('id','DESC')->find();
	    $qihao =$info['qihao'];  
		
		$aa = self:: getCurrentResult($qihao);
		
		foreach ($aa as $key=>$it){
	    	$single = $it['single'];
			$double = $it['double'];
			$big = $it['big'];
			$small = $it['small'];
			$zonghe[$key] =  intval($it['single'])+intval($it['double'])+intval($it['big'])+intval($it['small']);
			if(intval($single)+intval($double)+intval($big)+intval($small)>0){
					
				($big>$small) ? $dig_small=2:$dig_small=1;
				($single>$double) ? $sin_dou=4: $sin_dou=3;
				$kjj[$key] = $this->res($dig_small,$sin_dou,$key);
				if($key!=86){
					$he +=$zonghe[$key];
					$ks[]=$key;
				}
			}
			
		}
		if(!empty($kjj)){
			if($zonghe[86]>=$he){
				$kjj = max($kjj);
			}else{
				foreach($weizhi as $v=>$item){
					if(in_array($v, $ks)!==false){
						$jg[$v] = $kjj[$v];
					}else{
						$jg[$v] = rand(0, 9);
					}
				}
				$kjj = implode('',$jg);
			}
		}else{
			$kj = '';
			for ($i = 0; $i < 5; $i++) {$kj .= mt_rand(0, 9);	}
			$kjj = $kj;
		}
		
		return $kjj;
	}
	//大小单双
	public function res($size,$dans,$filter){
		//开奖状态：大（23~45），小（0~22），单（和值不能被2整除），双（和值能被2整除）
		// 和是小单 0-9 10个数 5个位置
        //小单
		if($size==2 && $dans==3){
			if($filter==86){		        
				$sum=$this->rand_sum(1,21);
				if($sum%2==0){$sum=$sum+1; }		
				echo '小单'.$sum."<br>";
			}else{
				$sum=$this->rand_sum(1,3);
				if($sum%2==0){$sum=$sum+1; }
				echo '小单'.$sum."<br>";
			}		
		}
		//小双
		if($size==2 && $dans==4){
			if($filter==86){
				$sum=$this->rand_sum(0,21);
				 if($sum%2==1){$sum=$sum+1; }
				 echo '小双'.$sum."<br>";
			}else{
				$sum=$this->rand_sum(0,4);
				if($sum%2==1){$sum=$sum+1; }
				echo '小双'.$sum."<br>";
			}
		}
		//大单
		if($size==1 && $dans==3){
			if($filter==86){		
			   	 $sum=$this->rand_sum(23,44);
				 if($sum%2==0){$sum=$sum+1; }
				 echo '大单'.$sum."<br>";
			}else{
				 $sum=$this->rand_sum(5,9);
				 if($sum%2==0){$sum=$sum+1; }
				 echo '大单'.$sum."<br>";
			}
		}
	
	    //大双
		if($size==1 && $dans==4){
			if($filter==86){
			   	 $sum=$this->rand_sum(23,43);
				 if($sum%2==1){$sum=$sum+1; }
				 echo '大双'.$sum."<br>";
			}else{
				$sum=$this->rand_sum(6,8);
				if($sum%2==1){$sum=$sum+1; }
				echo '大双'.$sum."<br>";
			}
		}
		if($filter==86){
			$kj = $this->arr_kjjg($sum);
		}else{
			$kj = $sum;
		}
	return	$kj;
}

    public  function arr_kjjg($sum){
	
	    $arr_kj ='';
		$arr_kj1 = $this->rand_num($sum-5);
		$arr_kj2 = $this->rand_num($sum-$arr_kj1-4); 
		$arr_kj3 = $this->rand_num($sum-$arr_kj1-$arr_kj2-3); 
		$arr_kj4 = $this->rand_num($sum-$arr_kj1-$arr_kj2-$arr_kj3-2); 
		$arr_kj5 = $sum-$arr_kj1-$arr_kj2-$arr_kj3-$arr_kj4 ;	  
	   
	   if($arr_kj5>10){	   
 		    $arr_kj1=$this->rand_sum($sum/5,9);			
		 	$arr_kj2=$this->rand_sum(($sum-$arr_kj1)/4,9);
			$arr_kj3=$this->rand_sum(($sum-$arr_kj1-$arr_kj2)/3,9); 
			$arr_kj4=$this->rand_sum( (($sum-$arr_kj1-$arr_kj2-$arr_kj3)/2),9);
			$arr_kj5 = $sum-$arr_kj1-$arr_kj2-$arr_kj3-$arr_kj4 ;
	   }
		$arr_kj .=$arr_kj1;
		$arr_kj .=$arr_kj2;
		$arr_kj .=$arr_kj3;
		$arr_kj .=$arr_kj4;
		$arr_kj .=$arr_kj5;
	return $arr_kj;
	}

 //取随机数
	public function rand_num($max){
		
		if($max<0){	$max=0; }	
		if($max>9){	$max=9;	}	
		
		$num= mt_rand(0,$max);
	 return   $num;
	}
	
	//取大小单双和
	 function rand_sum($min,$max){
		$sum= mt_rand($min,$max);
	 return   $sum;
	}





/************************************开奖   END ****************************************************/ 

    /**
     * 获取开奖数据并执行后续操作
     */
    public function index()
    {
       
		//查看过滤是否开启
	    $info = Db::name('caipiao_open')->where(['czid'=>$this->czid])->column('filter','wfid');
	    $filter = array_filter($info);
	    if(empty($filter)){
	    	$kjj = '';
	    	for ($i = 0; $i < 5; $i++) {$kjj .= mt_rand(0, 9);	}
	    }else{
	    	$kjj = $this->kj_index();
	    }
	    /* if(0==$info['filter']){
	    	$kjj = '';
	    	for ($i = 0; $i < 5; $i++) {$kjj .= mt_rand(0, 9);	}
	    }else{
	    	$kjj = $this->kj_index();
	    } */
		 echo $kjj;
	
	
		 echo "---------- 开始处理当期数据 ----------<br/><br/>";
        //获取最新应开奖期号
        $info = Db::name('kjjg_list')
            ->where(['czid' => $this->czid, 'kjjg' => '0'])
            ->field('qihao,jztime')
            ->where('jztime', '<', $this->time)
            ->order('id', 'DESC')
            ->find();
        $que = Db::name('caipiao')->where(['czid'=>$this->czid,'qihao'=>$info['qihao']])->find();
        if($que){
        	$kjj = explode(',', $que['kjjg']);
        	$kjj = implode('', $kjj);
        }
        //无数据情况补足
        if (!$info) {
            $timestamp = strtotime(date('Y-m-d H:i', $this->time) . ':00');
            $info['qihao'] = date('YmdHi', $timestamp);
            $info['jztime'] = $timestamp;
        }
        $result = array(
            'qihao' => $info['qihao'],
            'czid' => $this->czid,
            'opencode' => $kjj,
            'pentime' => date('Y-m-d H:i:s', $this->time),
            'opentimestamp' => $this->time,
        );

        $result_json = json_encode($result);
        $this->insertDataRedis($result_json);

        //开奖结果入库
        $this->kjjgSave($this->czid, $info['qihao'], $info['jztime'], $kjj);
        //将最新开奖数据存入Redis
        $this->redis->set("result_{$this->czid}", "{$info['qihao']},{$info['jztime']},{$kjj}");

        echo "<br/>---------- 处理当期数据完成 ----------<br/>";

        //生成新期数据
        $this->processingNew($info['qihao']);
        usleep(10000);
        //中奖结算
		
        $this->payment();
    }


    /**
     * 执行开奖数据入库操作
     */
    private function kjjgSave($czid, $qihao, $jztime, $kjjg_string)
    {
        // 查询是否存在本期
        $exist = Db::name('kjjg_list')->where(['qihao' => $qihao, 'czid' => $czid])->find();

        if ($exist) {
            if (!$exist['iftz']) {
                Db::name('kjjg_list')->where('id', $exist['id'])->data(['kjjg' => $kjjg_string, 'iftz' => 1])->update();
                echo "{$czid} 号彩第 {$qihao} 期数据更新成功<br/>";
            }
        } else {
            Db::name('kjjg_list')->data(['czid' => $czid, 'qihao' => $qihao, 'jztime' => $jztime, 'kjjg' => $kjjg_string, 'iftz' => 1])->insert();
            echo "{$czid} 号彩第 {$qihao} 期数据写入成功<br/>";
        }
    }

    /**
     * 生成新期数据
     */
    private function processingNew($last_qihao)
    {
        echo "<br/>---------- 开始生成下期数据 ----------<br/><br/>";
        //$data = Db::name('time')->where('czid', $this->czid)->where('jztime', '>=', date('H:i:s', $this->time))->order('id', 'ASC')->find();
        $data = Db::name('time')
        ->alias('t')
        ->join('__CAIPAI_LIST__ cl','cl.id=t.czid')
        ->field('t.*,cl.cp_fp_time')
        ->where('t.czid',$this->czid)->where('t.jztime','>=',date('H:i:s',$this->time))->order('t.id','ASC')->find();
        
	        //分分时时彩
	        $sz_time = strtotime(date('Y-m-d') . $data['jztime']);
	        if(empty($data)){
	        	$qihao = date('YmdHi', strtotime(date('Y-m-d ', strtotime('+1 day')).'00:00:00'));
	        	$sz_time = strtotime(date('Y-m-d ',strtotime('+1 day')).'00:00:00' );
	        }else{
	        	 $qihao = date('YmdHi', strtotime(date('Y-m-d') . $data['jztime']));
	        } 
	      
	        $sz_time = floor($sz_time)-floor($data['cp_fp_time']);
	      
	        $this->insertNew($this->czid, $qihao, $sz_time, '');
        //将当期期号存入redis，生成新期后此期便作为上一期，便于后续操作
        $this->redis->set("secend_{$this->czid}", "{$last_qihao}");

        //检查新期是否存在追号
        $trace_num = Db::name('touzhu_list_zh')->where(['czid' => $this->czid, 'qihao' => ['<=',$qihao]])->select();
        if ($trace_num) {
            foreach ($trace_num as $vt) {

                $data = array(
                    'czid' => $vt['czid'], 'qihao' => $vt['qihao'], 'tzhm' => $vt['tzhm'], 'tzje' => $vt['tzje'], 'dzje' => $vt['dzje'],
                    'tzzs' => $vt['tzzs'], 'username' => $vt['username'], 'tzhje' => $vt['tzhje'], 'zjje' => $vt['zjje'],
                    'ifqs' => $vt['ifqs'], 'wfid' => $vt['wfid'], 'dqpl' => $vt['dqpl'], 'xzfd' => $vt['xzfd'], 'fdje' => $vt['fdje'],
                    'kjjg' => $vt['kjjg'], 'zjzs' => $vt['zjzs'], 'nbzh' => $vt['nbzh'], 'tz_time' => $vt['tz_time'],'method'=> $vt['method']
                );
				$data['from'] = 1==intval($vt['stop']) ? 1 : 2;
                Db::startTrans();
                try {
                    Db::name('touzhu_list_no')->data($data)->insert();
                    Db::name('touzhu_list_zh')->data($data)->where('id', $vt['id'])->delete();
                    Db::commit();
                    echo "{$vt['czid']} 号彩第 {$qihao} 期追号更新成功<br/>";
                } catch (\Exception $e) {
                    Db::rollback();
                    echo "{$vt['czid']} 号彩第 {$qihao} 期追号更新失败<br/>";
                }
                usleep(10000);
            }
        }

        echo "<br/>---------- 生成下期数据完成 ----------";
    }

    /**
     * 新期写入库
     */
    private function insertNew($czid, $qihao, $jztime, $pss)
    {
        $res = Db::name('kjjg_list')->where(['czid' => $czid, 'qihao' => $qihao])->find();
        if (!$res) {
            Db::name('kjjg_list')->data(['czid' => $czid, 'qihao' => $qihao, 'jztime' => $jztime, 'kjjg' => '0', 'iftz' => 0, 'ps' => $pss])->insert();
            echo "{$czid} 号彩第 {$qihao} 期新期写入成功";
            $this->insertNewRedis($czid, $qihao, $jztime);
        }
    }

    /**
     * 新期写入Redis
     */
    private function insertNewRedis($czid, $qihao, $jztime)
    {
        $this->redis->set("{$czid}", "{$qihao},{$jztime},0");
        echo " Redis写入成功<br/>";
    }

    /**
     * 最新开奖数据写入Redis
     */
    private function insertDataRedis($data)
    {
        $this->redis->set('ffc_kjjg', "{$data}");
        @file_put_contents('./ffclog/newdata/' . date('Ymd', $this->time) . '.txt', $data . "\n", FILE_APPEND);
    }

    /**
     * 开奖结算
     */
    private function payment()
    {
        
        echo "<br/><br/>---------- 开始处理结算统计 ----------<br/>";
        $ctime = microtime(true);
        $cur_time = time();
        //非关联方式，循环查询
        /* $data_all = Db::name('touzhu_list_no')->alias('t')
                            ->join('__USERNAME__ u','t.username=u.username')
                            ->field('t.*,u.id as user_id,u.swzh,u.nbzh as nb')
                            ->where('t.czid','62')
                            ->limit(1000)
                            ->select(); */
        //关联方式，但因为开奖表数据量大，效率待定，具体说明参看logic->FfcPayment
        $data_all = Db::name('touzhu_list_no')->alias('t')
            ->join('__KJJG_LIST__ k', 't.czid=k.czid and t.qihao=k.qihao')
            ->join('__USERNAME__ u', 't.username=u.username')
            ->field('t.*,k.kjjg,u.id as user_id,u.swzh,u.nbzh as nb')//k.kjjg务必放在t.*之后
            ->where('k.kjjg', '<>', '0')
            ->where('t.czid', '62')
            ->limit(1000)
            ->select();
        $count = count($data_all);
        foreach ($data_all as $v) {
            $ffc = FfcPayment::getInstance();
            $payment_result = $ffc->dealInfo($v);
            if ($payment_result !== false) {
                $this->sendMessage($v['username'], '分分时时彩', '分分时时彩', $v['qihao'], $payment_result);
            }
        }
        $time = microtime(true) - $ctime;
        $ymd = date('Y-m-d H:i:s', $cur_time);
        @file_put_contents('./ffclog/payment/' . date('Ymd', $cur_time) . '.txt', "{$ymd}，用时{$time}s，可处理{$count}条\n", FILE_APPEND);
        echo "<br/>{$time}，{$count}<br/>";
        echo "<br/>---------- 结算统计处理完成 ----------<br/>";
    }

    /**
     * 会员消息发送
     */
    private function sendMessage($username, $cp_name_old, $cp_name_new, $qihao, $zjje)
    {
        if (!$cp_name_new) $cp_name_new = $cp_name_old;
        $message = "您投注的:【{$cp_name_new}】，【{$qihao}】期已开奖，中奖金额:【{$zjje}】元！";
        $data = array(
            'username' => $username,
            'test' => $message,
            'xx_time' => $this->time,
            'ifdq' => 0
        );
        Db::name('xiaoxi')->data($data)->insert();
    }
}
